package pl.edu.agh.winmon.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

/**
 * Abstract class providing utility methods for DAO classes.
 */
public abstract class AbstractDAOSupport {

	/**
	 * Hibernate's {@link SessionFactory} which manages communication with database.
	 */
	protected SessionFactory sessionFactory;

	/**
	 * Constructor.
	 *
	 * @param sessionFactory
	 *            Hibernate's {@link SessionFactory} which manages communication with database.
	 */
	public AbstractDAOSupport(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Returns list that satisfies specified {@link Criteria}.
	 *
	 * @param criteria
	 *            Search criteria.
	 * @return List that satisfies specified {@link Criteria}.
	 */
	@SuppressWarnings("rawtypes")
	public List findByCriteria(DetachedCriteria criteria) {
		return findByCriteria(criteria, 0);
	}

	/**
	 * Returns list that satisfies specified {@link Criteria}.
	 *
	 * @param criteria
	 *            Search criteria.
	 * @param maxResult
	 *            Result limit. 0 - not constraied.
	 * @return List that satisfies specified {@link Criteria}.
	 */
	@SuppressWarnings("rawtypes")
	public List findByCriteria(DetachedCriteria criteria, int maxResult) {
		if (maxResult < 0) {
			throw new IllegalArgumentException("Size of maximal result set should be greater than 0"); //$NON-NLS-1$
		}

		List resuList = null;

		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();

		Criteria crit = criteria.getExecutableCriteria(session);
		if (maxResult != 0) {
			crit.setMaxResults(maxResult);
		}
		resuList = crit.list();

		session.getTransaction().commit();
		
		return resuList;
	}

	public Serializable save(Object object) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();

		Serializable result = session.save(object);

		session.getTransaction().commit();

		return result;
	}
}
